package cn.dwj.hadoop.mr.ii;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by Administrator on 2017/12/29 0029.
 */
public class InverseIndexStepTwo {
    public static class SteTwoMapper extends Mapper<LongWritable, Text, Text, Text>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //拿到一行数据
            String line = value.toString();
            String[] fields = StringUtils.split(line, "\t");
            String[] wordAndFileName = StringUtils.split(fields[0], "-->");

            String word = wordAndFileName[0];
            String fileName = wordAndFileName[1];
            long count = Long.parseLong(fields[1]);

            context.write(new Text(word), new Text(fileName+"-->"+count));
            //输出结果形式：<hello, a.txt-->3>
        }
    }

    public static class SteTwoReduce extends Reducer<Text, Text, Text, Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            //拿到的数据<hello,{a.txt-->3, b.txt-->2, c.txt-->1}>
            String result = "";
            for(Text value : values){
                result = result + value.toString() + "";
            }

            context.write(key, new Text(result));
            //输出的结果就是k:hello   v:a.txt-->3 b.txt-->2 c.txt-->1
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        //设置整个job所在的那些类在哪个jar包中
        job.setJarByClass(InverseIndexStepTwo.class);
        //本job使用的map和reduce的类
        job.setMapperClass(SteTwoMapper.class);
        job.setReducerClass(SteTwoReduce.class);

        //指定输出数据的类型，对mapper和reduce的类型都起作用
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job, new Path[]{new Path("")});
        Path output = new Path("");
        FileSystem fs = FileSystem.get(conf);
        if(fs.exists(output)){
            fs.delete(output, true);
        }
        FileOutputFormat.setOutputPath(job, output);//指定处理结果输出数据存放在路径

        System.exit(job.waitForCompletion(true)?0:1); //将job提交给集群运行过程要不要提示出来


        //如果多个job一起
        if(job.waitForCompletion(true)){
            //执行另外一个job
        }
    }
}
